#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>

#include <cstdlib>

#include "dispatcher.h"
#include "backup_server_connection.h"

void on_download_complete(backup_server_connection::request req,
                          char* data,
                          size_t num_bytes)
{
    std::cout << "received " << num_bytes << " bytes of data"
              << " | piece_size: " << req.piece_size 
              << " | index: " << req.index
              << " | count: " << req.count
              << std::endl;

    // You are now the owner of the data buffer, with the
    // responsibility to delete it when done!
    delete [] data;
}

int main()
{

    std::cout << std::endl << "dispatcher_test running..." 
              << std::endl << std::endl;

    dispatcher disp;

    backup_server_connection connection("cowboycoders.se", 
                                        "22234", 
                                        "big_buck_bunny", 
                                        disp,
                                        10);

    while(true) 
    {
        std::string input_str;
        std::getline(std::cin, input_str);

        if(input_str == "quit" || input_str == "q") 
        {

            break;
        } 
        else if(input_str != "")
        {
            boost::tokenizer<> tok(input_str);
            boost::tokenizer<>::iterator it=tok.begin();

            size_t params[3];
            
            int i;
            for(i = 0; i < 3 && it != tok.end(); ++i, ++it) {
                params[i] = atoi(it->c_str());
            }

            if(i == 3) {
                backup_server_connection::request 
                    request(params[0], params[1], params[2]);

                connection.send(request, on_download_complete);
            } else {
                std::cout << "syntax: size index count (unit: B, limit 1 MiB)"
                          << std::endl;
            }
        }
    }


    return 0;
}
